package com.peng.sell.controller;

import com.peng.sell.dataobject.ProductCategory;
import com.peng.sell.dataobject.ProductInfo;
import com.peng.sell.enums.ResponseCodeEnum;
import com.peng.sell.form.CategoryForm;
import com.peng.sell.service.ProductCategoryService;
import com.peng.sell.utils.PageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/seller/category")
public class SellerCategoryController {

    @Autowired
    ProductCategoryService productCategoryService;


    @GetMapping("/list")
    public String list(Map<String, Object> dataMap) {
        List<ProductCategory> data = productCategoryService.findAll();
        dataMap.put("data", data);
        return "/category/list";
    }

    @GetMapping("/index")
    public String index(@RequestParam(value ="categoryId",required = false) Integer categoryId,Map<String,Object> map){
        if(categoryId!=null){
            ProductCategory category = productCategoryService.findOne(categoryId);
            map.put("category",category);
        }
        return "/category/index";
    }
    @PostMapping("/save")
    public String save(@Validated  CategoryForm categoryForm, BindingResult bindingResult, Map<String,Object> map){
        if(bindingResult.hasErrors()){
            map.put("msg",bindingResult.getFieldError().getDefaultMessage());
            map.put("url","/sell/seller/category/index");
            return "/common/error";
        }
        ProductCategory category = new ProductCategory();
        if(categoryForm.getCategoryId()!=null){
             category = productCategoryService.findOne(categoryForm.getCategoryId());
        }
        BeanUtils.copyProperties(categoryForm,category);
        try{
            productCategoryService.save(category);
        }catch (Exception e){
            map.put("msg",e.getMessage());
            map.put("url","/sell/seller/product/list");
            return "/common/error";
        }
        map.put("url","/sell/seller/category/list");
        return "/common/success";
    }
}
